<?php
namespace app\admin\controller;
use think\Controller;


class Problem extends AdminBase {
	//添加问题的页面展示	权限:添加问题
	public function add() {
		if(!$this->have_power(1)) {
			$this->error('对不起，您没有对应的权限！',url('admin/index/welcome'));
		}
		return $this->fetch();
	}
	//问题列表的页面展示	权限:编辑问题
	public function editor() {
		if(!$this->have_power(0)) {
			$this->error('对不起，您没有对应的权限！',url('admin/index/welcome'));
		}
		$list = db('problem')->field('problem_id,in_date,title,defunct')->order('problem_id ASC')->paginate();
		$lists = $list->items();
		$this->assign('list',$lists);
		$this->assign('keyword','');
		$this->assign('page',$list->render());
		return $this->fetch();
	}
	//重判问题页面展示    权限:重判问题
	public function rejudge() {
		if(!$this->have_power(2)) {
			$this->error('对不起，您没有对应的权限！',url('admin/index/welcome'));
		}
		return $this->fetch();
	}
	//重判问题逻辑
	public function rejudge_opt() {
		if(!$this->have_power(2)) {
			$this->error('对不起，您没有对应的权限！',url('admin/index/welcome'));
		}
		$name = input('name');
		$val = input('val');
		db('solution')->where($name,$val)->update(['result'=>'1']);
		$this->success('开始重判！',url('admin/problem/rejudge'));
	}
	//添加问题的逻辑实现	权限:添加问题
        private function get_data(){
            $data['title']=input('title','Problem','trim');
            $data['time_limit']=input('time_limit','Problem','trim');
            $data['memory_limit']=input('memory_limit','Problem','trim');
            $data['description']=input('description','Problem','trim');
            $data['input']=input('input','','trim');
            $data['output']=input('output','','trim');
            $data['sample_input']=input('sample_input','','trim');
            $data['sample_output']=input('sample_output','','trim');
            $data['hint']=input('hint','','trim');
            $data['source']=input('source','','trim');
            $data['spj']=input('spj',0,'trim');
            $data['defunct']=input('defunct','N','trim');
            $data['accepted']=0;
            $data['submit']=0;
            $data['solved']=0;
            $data['in_date']=date('Y-m-d H:i:s',time());
            $data['score']= input('socre',0,'intval');
            $data['user_id']= $this->user_id;
            return $data;
        }
        public function add_opt() {
		if(!$this->have_power(1)) {
			$this->error('对不起，您没有对应的权限！',url('admin/index/welcome'));
		}
		$data= $this->get_data();
                $res=db('problem')->insert($data);
                dump($res);
		if(!$this->have_power(0)) {
			$this->success('添加成功！',url('admin/index/welcome'));
		} else {
			$this->success('添加成功！',url('admin/problem/editor'));
		}
	}
	//编辑问题    权限:编辑问题
	public function editor_opt() {
		if(!$this->have_power(0)) {
			$this->error('对不起，您没有对应的权限！',url('admin/index/welcome'));
		}
		$flag = input('flag');
		$id = input('id');
		if($flag=='1') {//展示问题信息
			$data = db('problem')->where(['problem_id'=>$id])->find();
			$this->assign('data',$data);
			return $this->fetch();
		} else {//更新问题信息
//                    dump($_POST);
//                    return ;
			$problem = model('Problem');
			$problem->allowField(true)->isUpdate(true)->save($_POST,['problem_id'=>$id]);
			$this->success('更新成功！',url('admin/problem/editor'));
		}
	}
	//搜索问题    权限:编辑问题
	public function search() {
		if(!$this->have_power(0)) {
			$this->error('对不起，您没有对应的权限！',url('admin/index/welcome'));
		}
		$val = input('keyword');
		if($val == '') {
			$list = db('problem')->where(1)->paginate();
		} else {
			$list = db('problem')->where('title','like',"%$val%")->whereOr(['problem_id'=>$val])->paginate();
		}
		$lists = $list->items();
		$this->assign('list',$lists);
		$this->assign('keyword',$val);
		$this->assign('page',$list->render());
		return $this->fetch('problem/editor');
	}
	//删除问题    权限:编辑问题
	public function del() {
		if(!$this->have_power(0)||!$this->have_power(10)) {
			$this->error('对不起，您没有对应的权限！',url('admin/index/welcome'));
		}
		db('problem')->delete(input('id'));
		$this->success('删除成功！',url('admin/problem/editor'));
	}
        public function test_data() {
        $pid = input('pid', 0, 'intval');
        if ($pid <= 0) {
            return;
        }
        $filelist = array();
        $key = 0;
        $tmp_path= config('judge.data_path').$pid.'/';
        $dir =@opendir($tmp_path);
        if($dir==false){
            mkdir($tmp_path);
            $dir =opendir($tmp_path);
        }
        while (($filename = readdir($dir)) !== false) {
            if ($filename != "." && $filename != "..") {
                $filelist[$key]['filename'] = $filename;
                $key++;
            }
        }
        //dump($filelist);
        $this->assign('pid',$pid);
        $this->assign('filelist',$filelist);
        return $this->fetch();
    }
    private function get_problem_status($pid){
        $res=db('problem')->find($pid);
        if(empty($res)) {
            return FALSE;
        }
        return $res['defunct'];
    }

    public function change_status(){
        $pid=input("pid",null,"intval");
        if($pid==null)
        {
            $ret['code']=1;
            $ret['msg']='未传入正确参数';
            return json($ret);
        }
        $ret['code']=0;
        if($this->user_id==''){
            $ret['code']=1;
            $ret['msg']='未登录';
            return json($ret);
        }
        if(!$this->have_power(0)){
            $ret['code']=1;
            $ret['msg']='对不起,您没有权限';
            return json($ret);
        }
        $status= $this->get_problem_status($pid);
        if($status==FALSE){
            $ret['code']=1;
            $ret['msg']='该题目不存在';
            return json($ret);
        }
        $set='N';
        if($status=='N') {
            $set='Y';
        }
        db('problem')->where('problem_id='.$pid)->setField('defunct',$set);
        $ret['msg']='更改成功';
        $ret['status']=$set;
        return json($ret);
    }

        public function download(){
        if(!$this->have_power(0)||!$this->have_power(1)){
            $this->error('对不起,您没有权限,请联系高级管理员');
            return ;
        }
//        dump($_GET);
//        return ;
        
        
        $pid= input('pid',0,'intval');
        $filename=input('filename',"",'trim');
        $filename= urldecode($filename);
        if($pid==0||$filename==""){
            echo 'null';
        }
        else {
            $filepath= config('judge.data_path').$pid.'/'.$filename;
//            echo $filepath;
    //            return ;
            header("Content-Type: application/octet-stream");
            header("Accept-Ranges: bytes");
            header("Accept-Length: " . filesize($filepath));
            header("Content-Disposition: attachment; filename=".$filename);
            $fp = fopen($filepath, 'rb');
            while(!feof($fp)){
                echo fread($fp, 1024*1024*2);
                @ob_flush(); 
                flush(); 
            }
        }
    }
    public function del_test_data(){
        if(!$this->have_power(0)){
            $this->error('对不起,您没有权限,请联系高级管理员');
            return ;
        }
        $pid= input('pid',0,'intval');
        $filename=input('filename',"",'trim');
        $filename= urldecode($filename);
        $filepath= config('judge.data_path').$pid.'/'.$filename;
        $res="";
        if(is_file($filepath)){
            $res=unlink($filepath);
        }
        else {
            $res=$this->delDirAndFile($filepath,true);
        }
        if($res==false){
            $this->error("删除失败,检查文件权限");
            return ;
        }
        $this->success('删除成功',url('admin/problem/test_data',['pid'=>$pid]));
    }
}
